package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.product.api.vo.SkuPriceVo;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.api.domain.ProductSkuVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-03-04
 */
@Slf4j
@Service
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {

        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;
    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        // 查询一个商品的所有sku
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getProductId, id)
                .select(ProductSku::getId, ProductSku::getSkuSpec);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);
        // 封装数据
        Map<String,Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }

    /*
     * 使用分布式锁解决缓存击穿问题(缓存过期时,加分布式锁)
     * 根据SkuID查询SKU商品信息
     *
     * @param skuId
     * @return
     */
    @Override
    public ProductSku getProductSku(Long skuId) {

        //判断缓存中是否存在数据
        String dataKey = "product:sku:" + skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
        //如果存在则直接返回
        if (productSku != null) {
            log.info("命中缓存：{}", dataKey);
            return productSku;
        }

        //加分布式锁
        String lockKey = "product:sku:lock:" + skuId;
        String lockValue = UUID.randomUUID().toString().replaceAll("-", "");
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 3, TimeUnit.SECONDS);
        if (flag) {
            try {
                //再次查询缓存
                productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
                //如果存在则直接返回
                if (productSku != null) {
                    log.info("命中缓存：{}", dataKey);
                    return productSku;
                }

                //如果不存在则从数据库中查询
                System.out.println("查询数据库");
                productSku = baseMapper.selectById(skuId);
                long ttl = productSku == null ? 1 : 10;
                if (productSku == null) {
                    productSku = new ProductSku(); //防止再次查询出来之后的值是null
                }

                //查询后将数据放入缓存
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.MINUTES);

                //返回数据
                return productSku;
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放分布式锁
                String script = """
                    if redis.call('get', KEYS[1]) == ARGV[1] then
                        return redis.call('del', KEYS[1])
                    else
                        return 0
                    end
                    """;
                Boolean result = (Boolean) redisTemplate.execute(
                        new DefaultRedisScript<>(script, Boolean.class),
                        Arrays.asList(lockKey),
                        lockValue
                );
                System.out.println("result = " + result);
            }
        } else {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //重试
            return getProductSku(skuId);
        }
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        //根据skuid列表批量查询商品的最新价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ProductSku::getId, skuIdList);
        queryWrapper.select(ProductSku::getId, ProductSku::getSalePrice);
        List<ProductSku> productSkuList = baseMapper.selectList(queryWrapper);

        if(!CollectionUtils.isEmpty(productSkuList)){
            return productSkuList.stream()
                    .map(productSku -> {
                        SkuPriceVo skuPriceVo = new SkuPriceVo();
                        skuPriceVo.setSalePrice(productSku.getSalePrice());
                        skuPriceVo.setSkuId(productSku.getId());
                        return skuPriceVo;
                    })
                    .collect(Collectors.toList());
        }

        return null;
    }

    @Override
    public ProductSkuVo getProductSkuVo(Long skuId) {
        return null;
    }

}
